/*
 *  atBudget Personal Finance Management application
 *
 *  Copyright 2011, Ilia Frenkel <frenkel.ilia@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
	Currencies controller handles all interactions with currencies.
 */
Ext.define('ATB.controller.Currencies', {
    extend: 'Ext.app.Controller',
	views: [
		'currency.List',
		'currency.Create',
		'currency.Edit',
		'currency.Manage'
	],
	stores: [
		'Currencies'
	],
	models: [
		'Currency'
	],
	/*
		Setup event handlers.
	*/
    init: function() {
		this.control({
			'currencylist': {
				itemdblclick: this.editCurrency
			},
			'currencyedit textfield': {
				change: this.updateExample
			},
			'currencycreate textfield': {
				change: this.updateExample
			},
			'currencymanage currencylist': {
				selectionchange: this.setButtonsState
			},
			'currencymanage': {
				show: this.refreshStore
			},
			'currencymanage button[action=editcurrency]': {
				click: this.openEditCurrency
			},
			'currencymanage button[action=addcurrency]': {
				click: this.openNewCurrency
			},
			'currencymanage button[action=deletecurrency]': {
				click: this.deleteCurrency
			},
			'currencyedit button[action=save]': {
				click: this.updateCurrency
			},
			'currencycreate button[action=save]': {
				click: this.createCurrency
			}
		});//this.control
    },//init

	/*
		Open edit currency dialogue and load currency information.
		This is an event handler for currencies list double click action.
		Parameters:
			grid   - grid panel that the user double clicked
			record - currency record that the user double clicked on
	*/
	editCurrency: function(grid, record) {
		var view = Ext.widget('currencyedit');
		view.down('form').loadRecord(record);
	},//editCurrency

	/*
		The same as editCurrency but for "Edit" button on the toolbar.
		Since we don't have reference to the grid or selected record
		we have to find out which record is selected and then call 
		editCurrency method. If no records are selected an error message
		will be shown.
	*/
	openEditCurrency: function (button) {
		var win  = button.up('window'),
			grid = win.down('currencylist'),
			sel  = grid.getSelectionModel(),
			recs = sel.selected;
			if (recs.items.length <= 0) {
				Ext.Msg.alert('Error', 'Please select one of the currencies first.');
			} else {
				this.editCurrency(grid, recs.items[0]);
			}
	},//openEditCurrency

	/*
		Open new currency dialogue. Nothing exciting here - just create
		the view.
	*/
	openNewCurrency: function() {
		var view = Ext.widget('currencycreate');
	},//openNewCurrency

	/*
		An event handler for "Save" button in the edit currency dialogue.
		Collects the values from the form, updates the record and calls
		sync on the store which triggers communication with the server.
		Any error during the communication is handled by the model's proxy.
	*/
	updateCurrency: function(button) {
		var win    = button.up('window'),
			form   = win.down('form'),
			record = form.getRecord(),
			values = form.getValues();

		record.set(values);
		this.getCurrenciesStore().sync();
		record.commit();
		win.close();
	},//updateCurrency
	
	/*
		An event handler for "Save" button in the create currency dialogue.
		Collects the values from the form, create new record, adds it to
		the store and calls	sync on the store which triggers communication
		with the server. Any error during the communication is handled by 
		the model's proxy.
	*/
	createCurrency: function(button) {
		var win    = button.up('window'),
			form   = win.down('form'),
			values = form.getValues(),
			store  = this.getCurrenciesStore();

		var record = this.getCurrencyModel().create(values);

		store.add(record);
		store.sync();
		win.close();
	},//createCurrency

	/*
		An event handler for "Remove" button in the manage currencies dialogue.
		Asks for confirmation and if positive destroys the selected record.
		Any error during the communication is handled by the model's proxy.
	*/
	deleteCurrency: function(button) {
		var win    = button.up('window'),
			grid = win.down('currencylist'),
			sel  = grid.getSelectionModel(),
			recs = sel.selected;
		if (recs.items.length <= 0) {
			Ext.Msg.alert('Error', 'Please select one of the currencies first.');
		} else {
			var record = recs.items[0];
			Ext.Msg.show({
				title:'Are you sure?',
				msg: 'Are you sure you want to delete this currency?',
				buttons: Ext.Msg.YESNO,
				fn: function(buttonId) {
					if (buttonId == 'yes') {
						record.destroy();
					}
				},
				icon: 'atb-icon-question'
			});
		}
	},//deleteCurrency

	/*
		Updates the "Example" field in the "Create" and "Edit" dialogues.
		This field shows formatting example for the values specifed.
	*/
	updateExample: function(fld, newVal, oldVal, opts) {
		if (newVal == oldVal) return;
		var form       = fld.up('form');
		var values     = form.getValues();
		var rec        = this.getCurrencyModel().create(values);
		var exampleFld = form.down('displayfield[name=examplefmt]');
		exampleFld.setRawValue(rec.formatExample(rec));
	},//updateExample

	/*
		Event handler for currencies list. Disables/enables "Edit" and "Remove"
		buttons according to selection.
	*/
	setButtonsState: function(view, sel, opts) {
		var win    = view.view.up('window'),
			edtBtn = win.down('button[action=editcurrency]'),
			delBtn = win.down('button[action=deletecurrency]')
		if (sel.length > 0) {
			edtBtn.enable();
			delBtn.enable();
		} else {
			edtBtn.disable();
			delBtn.disable();
		}
	},//setButtonsState
	
	/*
		Refresh currencies store when manage currencies dialogue is shown to
		fetch any changes from the server before we make new ones.
	*/
	refreshStore: function() {
		this.getCurrenciesStore().load();
	}//refreshStore
});